package com.cz.basetool.ui_work.util.permission;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;

import com.cz.basetool.ui_work.interfaces.IActivityResultListener;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by XinYi on 2019/1/15.
 * 权限管理
 */

public class PermissionManager implements IActivityResultListener {
    private static final PermissionManager ourInstance = new PermissionManager();
    private OnPermissionRequestCallBack onPermissionRequestCallBack;
    private OnPermissionRequestCallBack tempOnPermissionRequestCallBack;            //临时回调，用于多个动态权限同时申请的场景。
    private int requestCodeTotal2;
    private int requestCodeTotal1;


    public static PermissionManager getInstance() {
        return ourInstance;
    }

    public void registOnPermissionRequestCallBack(OnPermissionRequestCallBack onPermissionRequestCallBack){
        this.onPermissionRequestCallBack = onPermissionRequestCallBack;
    }

    /**
     * 动态权限注册结果监听
     * @param tempOnPermissionRequestCallBack
     */
    private void registTempOnPermissionRequestCallBack(OnPermissionRequestCallBack tempOnPermissionRequestCallBack){
        this.tempOnPermissionRequestCallBack = tempOnPermissionRequestCallBack;
    }



    private PermissionManager() {

    }


    /**
     * 动态权限申请(单个)
     * @param activity
     * @param requestCodeOut                       申请码
     * @param permissionPrepare2Request            申请的权限
     * @return
     */
    public boolean requestPermission(Activity activity, final int requestCodeOut, String permissionPrepare2Request){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            int permissionCheck = ContextCompat.checkSelfPermission(activity, permissionPrepare2Request);
            if (permissionCheck == PackageManager.PERMISSION_GRANTED) {
                return true;
            } else {
                registTempOnPermissionRequestCallBack(new OnPermissionRequestCallBack() {
                    @Override
                    public void onGrantedSuccess(int requestCode) {
                        if(requestCodeOut == requestCode){
                            if(onPermissionRequestCallBack != null){
                                onPermissionRequestCallBack.onGrantedSuccess(requestCode);
                            }
                        }
                    }

                    @Override
                    public void onGrantedFailure(int requestCode) {
                        if(requestCodeOut == requestCode){
                            if(onPermissionRequestCallBack != null){
                                onPermissionRequestCallBack.onGrantedFailure(requestCode);
                            }
                        }
                    }
                });

                String[] deniedPermissions = new String[]{permissionPrepare2Request};
                ActivityCompat.requestPermissions(activity, deniedPermissions, requestCodeOut);
                return false;
            }
        }else{
            return true;
        }
    }

    /**
     * 动态权限申请(多个)
     * @param activity
     * @param requestCodeOut                         申请码
     * @param permissionPrepare2RequestList          申请权限（一个或者多个）
     * @return
     */
    public boolean requestPermission(Activity activity, final int requestCodeOut, String[] permissionPrepare2RequestList){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            List<String> permissionDeniedList = new ArrayList<>();
            for (String permission : permissionPrepare2RequestList) {
                int permissionCheck = ContextCompat.checkSelfPermission(activity, permission);
                if (permissionCheck == PackageManager.PERMISSION_GRANTED) {

                } else {
                    permissionDeniedList.add(permission);
                }
            }

            int requestBaseCode = -1;
            requestCodeTotal1 = 0;
            requestCodeTotal2 = 0;

            if (!permissionDeniedList.isEmpty()) {
                registTempOnPermissionRequestCallBack(new OnPermissionRequestCallBack() {
                    @Override
                    public void onGrantedSuccess(int requestCode) {
                        requestCodeTotal2 += requestCode;
                        //说明多个动态权限申请全部成功了
                        if(requestCodeTotal1 == requestCodeTotal2){
                            if(onPermissionRequestCallBack != null){
                                onPermissionRequestCallBack.onGrantedSuccess(requestCodeOut);
                            }
                        }
                    }

                    @Override
                    public void onGrantedFailure(int requestCode) {
                        if(requestCodeOut == requestCode){
                            if(onPermissionRequestCallBack != null){
                                onPermissionRequestCallBack.onGrantedFailure(requestCode);
                            }
                        }
                    }
                });

                //将权限
                for (int i = 0; i < permissionDeniedList.size(); i++) {
                    requestBaseCode = requestCodeOut + (i+1);
                    requestCodeTotal1 += requestBaseCode;
                    ActivityCompat.requestPermissions(activity, new String[]{permissionDeniedList.get(i)}, requestBaseCode);
                }
                return false;
            }else{
                return true;
            }
        }else{
            return true;
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(tempOnPermissionRequestCallBack != null){
            if(Activity.RESULT_OK == resultCode){
                tempOnPermissionRequestCallBack.onGrantedSuccess(requestCode);
            }else{
                tempOnPermissionRequestCallBack.onGrantedFailure(requestCode);
            }
        }
    }


    public interface OnPermissionRequestCallBack{
        /**
         * 动态权限注册成功
         * @param requestCode
         */
        void onGrantedSuccess(int requestCode);

        /**
         * 动态权限注册失败
         * @param requestCode
         */
        void onGrantedFailure(int requestCode);
    }
}
